import * as XLSX from 'xlsx'
import {API} from "@/utils/api"
import axios from "axios";
import {
    Message
} from "element-ui";
import {uploadUrl} from "@/api";

/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0 || !time) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string')) {
            if ((/^[0-9]+$/.test(time))) {
                // support "1548221490638"
                time = parseInt(time)
            } else {
                // support safari
                // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
                time = time.replace(new RegExp(/-/gm), '/')
            }
        }

        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        return value.toString().padStart(2, '0')
    })
    return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
    const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
    if (!search) {
        return {}
    }
    const obj = {}
    const searchArr = search.split('&')
    searchArr.forEach(v => {
        const index = v.indexOf('=')
        if (index !== -1) {
            const name = v.substring(0, index)
            const val = v.substring(index + 1, v.length)
            obj[name] = val
        }
    })
    return obj
}


/**
 * @description: 导出excel
 * @param {any} dataList
 * @param {Array} fields
 * @param {Array} headers
 * @param {string} fileName 需要加后缀名 eg: 'test.xlsx'
 * @param {string} sheetName
 * @return {*}
 */
export function exportExcel(dataList, fields, headers = [], fileName = 'Excel.xlsx', sheetName = 'Sheet') {
    let data = new Array()
    if (!Array.isArray(dataList)) return console.warn('dataList is not an array type')
    // if (!Array.isArray(fields)) return console.warn('fields is not an array type')
    // if (!Array.isArray(headers)) return console.warn('headers is not an array type')

    data = dataList.map((obj) => {
        return fields.map((field) => {
            return obj[field]
        })
    })
    if (headers.length > 0) {
        data.splice(0, 0, headers)
    } else {
        // 将headers设置为英文字段表头
        data.splice(0, 0, fields)
    }
    const ws = XLSX.utils.aoa_to_sheet(data) // 创建工作表
    const wb = XLSX.utils.book_new() // 创建工作簿

    // 隐藏表头
    // let wsrows = [{ hidden: true }]
    // ws['!rows'] = wsrows // ws - worksheet

    XLSX.utils.book_append_sheet(wb, ws, sheetName) // 将工作表添加到工作簿中
    XLSX.writeFile(wb, fileName) // 导出文件
}

// 全局图片拼接显示
export function get_head_img(url = null) {
    if (isImageUrl(url)) {
        return url;
    }
    if (url) {
        return API + url;
    } else {
        return require("@/assets/images/default.png")
    }
}

export function isImageUrl(url) {
    // 正则表达式来判断 URL 是否是网络图片地址
    const urlPattern = /^(https?:\/\/)?((?:www\.)?[\w-]+(\.[a-z]{2,})+)(\/[\w\-\.]+)+\.(jpg|jpeg|png|gif|bmp|webp)$/i;
    // 正则表达式来判断字符串是否是 Base64 编码的图片
    const base64Pattern = /^data:image\/(jpg|jpeg|png|gif|bmp|webp);base64,[A-Za-z0-9+/=]+$/i;

    return urlPattern.test(url) || base64Pattern.test(url);
}

// 传入数组 查询出ID对应的数据内容
export function findObjectById(array, id) {
    // 遍历数组
    for (let i = 0; i < array.length; i++) {
        const obj = array[i];
        // 如果当前对象的id匹配，则返回该对象
        if (obj.id === id) {
            return obj;
        }
        // 如果当前对象有子节点，并且子节点是一个数组，则递归调用findObjectById函数
        if (obj.children && Array.isArray(obj.children)) {
            const found = findObjectById(obj.children, id);
            // 如果在子节点中找到了匹配的对象，则返回该对象
            if (found) {
                return found;
            }
        }
    }
    // 如果未找到匹配的对象，则返回null
    return null;
}

// 下载文件
export function downloadFile(url) {
    if (!url) return Message.error("无文件下载");
    let fileName = decodeURIComponent(url.split('=').pop())
    axios({
        url: url,
        method: 'GET',
        responseType: 'blob', // 设置响应类型为二进制流
    }).then(res => {
        const blob = new Blob([res.data], {type: 'application/octet-stream'});
        const url = window.URL.createObjectURL(blob);

        const a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        a.style.display = 'none';
        document.body.appendChild(a);

        a.click();

        window.URL.revokeObjectURL(url);
    })
}

// 上传图片
export function uploadImage(file,next = ()=>{}) {
    let _this = this;
    let filename = file.name;
    // 使用正则表达式匹配文件后缀
    let extension = filename.match(/\.([^.]+)$/);
    // 如果匹配到了后缀，extension[1] 将包含后缀名，否则为 null
    let suffix = "."
    suffix += extension ? extension[1] : "png";
    const formData = new FormData();
    formData.append('total', 1);
    formData.append('index', 1);
    formData.append('mainway', 'pic');
    formData.append('filename', Date.now() + suffix);
    formData.append('data', file);
    // 使用Axios或其他HTTP库发送请求
    axios.post(uploadUrl, formData, {
        headers: {'Content-Type': 'multipart/form-data'}
    }).then(response => {
        console.log(response.data.path)
        next(response.data.path)
    })
}
